package com.nku.mason.masonframework.aop;

import java.util.List;
import java.lang.reflect.Method;
import java.util.ArrayList;

import net.sf.cglib.proxy.MethodProxy;

public class ProxyChain {
	
	private final Class<?> targetClass;
	private final Object targetObject;
	private final Method targetMethod;
	private final MethodProxy methodProxy;
	private final Object[] methodParams;
	
	private List<Proxy> proxyList = new ArrayList<Proxy>();
	private int proxyIndex = 0;
	
	public ProxyChain(Class<?> targetClass, Object targetObject, Method targetMethod, MethodProxy methodProxy,
			Object[] methodParams, List<Proxy> proxyList) {
		super();
		this.targetClass = targetClass;
		this.targetObject = targetObject;
		this.targetMethod = targetMethod;
		this.methodProxy = methodProxy;
		this.methodParams = methodParams;
		this.proxyList = proxyList;
	}
	
	public Object[] getMethodParams(){
		return methodParams;
	}
	
	public Class<?> getTargetClass(){
		return targetClass;
	}
	
	public Method getTargetMethod(){
		return targetMethod;
	}
	
	/**
	 * 通过proxyIndex来充当代理对象的计数器，若尚未达到proxyList的上限，则从proxyList中取出相应的Proxy对象，
	 * 并调用其doProxy方法。在Proxy接口的实现中会提供相应的横切逻辑，并调用doProxyChain方法，随后将再次调用当
	 * 前ProxyChain对象的doProxyChain方法，直到proxyIndex达到proxyList的上限为止，最后调用methodProxy
	 * 的invokeSuper方法，执行目标对象的业务逻辑。
	 * @return 返回代理链中各个代理增强逻辑的结果 或 目标方法执行的结果
	 * @throws Throwable
	 */
	public Object doProxyChain() throws Throwable{
		Object methodResult;
		if (proxyIndex < proxyList.size()) {
			methodResult = proxyList.get(proxyIndex++).doProxy(this);
		} else {
			methodResult = methodProxy.invokeSuper(targetObject, methodParams);
		}
		
		return methodResult;
	}
}



































































